package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.Comment;
import com.entity.Contact;
import com.entity.Project;
import com.util.DBHelp;
import com.util.RowMapper;

public class ContactDao {
	private DBHelp<Contact> db = new DBHelp<Contact>();
	
	private class ContactRowMapper implements RowMapper<Contact> {

		public Contact mapRow(ResultSet rs) throws SQLException {
			
			Contact c = new Contact();
			c.setId(rs.getString("id"));
			c.setName(rs.getString("name"));
			c.setEmail(rs.getString("email"));
			c.setHome(rs.getString("home"));
			c.setPhone(rs.getString("phone"));
			c.setTel(rs.getString("tel"));
			c.setAddress(rs.getString("address"));
			c.setAdstruct(rs.getString("adstruct"));
			c.setCompany(rs.getString("company"));
			
			Comment co=new Comment();
			co.setId(rs.getString("id"));
			co.setMessage(rs.getString("message"));
			co.setContactid(c.getId());
			c.setComment(co);
			
			Project p = new Project();
			c.setProjectid(rs.getString("projectid"));
			p.setId(c.getProjectid());
			p.setProjectName(rs.getString("projectname"));
			c.setProject(p);
			
			return c;
		}
		
		
	}

	public List<Contact> findAllContact() {
		String sql = "select tc.id,tc.`name`,tc.company,tc.phone,tc.tel,tc.email,tc.address,tc.home,tc.weibo,tc.adstruct,tc.createtime,tc.projectid,tco.id,tco.message from t_contact as tc left join t_comment as tco on tc.id=tco.contactid";
		return db.executeQueryForList(sql, new ContactRowMapper());
	}

	public void saveContact(Contact c) {
		String sql="insert into t_contact(id,`name`,company,phone,tel,email,address,home,weibo,adstruct,projectid) values (?,?,?,?,?,?,?,?,?,?,?)";
		db.executeSQL(sql, c.getId(),c.getName(),c.getCompany(),c.getPhone(),c.getTel(),c.getEmail(),c.getAddress(),c.getHome(),c.getWeibo(),c.getAdstruct(),c.getProjectid());
	}

	public Contact findContactByContactId(String id) {
		String sql = "select tc.id,tc.`name`,tc.company,tc.phone,tc.tel,tc.email,tc.address,tc.home,tc.weibo,tc.adstruct,tc.createtime,tc.projectid,tco.id,tco.message from t_contact as tc left join t_comment as tco on tc.id=tco.contactid where id=?";
		return db.executeQueryForObject(sql, new ContactRowMapper(),id);
	}

	public void updateContactById(Contact c,String id) {
		String sql="update to t_contact set `name`=?,set company=?,set phone=?,set tel=?,set email=?,set address=?,set home=?,set weibo=?,set adstruct=?,set=projectid=? where id=?";
		db.executeSQL(sql,c.getName(),c.getCompany(),c.getPhone(),c.getTel(),c.getEmail(),c.getAddress(),c.getHome(),c.getWeibo(),c.getAdstruct(),c.getProjectid(),id);
	}

	
}
